<template>
  <div class="app">
    <!-- 授权验证组件 -->
    <AuthGuard v-if="!isAuthenticated" @authorized="handleAuthorized" />
    
    <!-- 主应用内容 -->
    <template v-else>
      <Navigation @page-change="handleNavigationChange" :current-page="currentPage" />

    <!-- 项目管理页面 -->
    <div v-if="currentPage === 'projects'">
      <Header />
      <StatsBar :stats="stats" />
      <Controls :activeFilter="activeFilter" :searchQuery="searchQuery" @filter-change="handleFilterChange"
        @search-change="handleSearchChange" @create-project="handleCreateProject" />
      <MainContent :projects="filteredProjects" @update-project="handleUpdateProject"
        @delete-project="handleDeleteProject" />

      <!-- 创建项目弹窗 -->
      <CreateProjectModal v-model:visible="createModalVisible" @create="handleCreateProjectSubmit" />

      <!-- 分页组件 -->
      <div class="pagination-container" v-if="total > 0">
        <div class="pagination-info">
          共 {{ total }} 条记录，第 {{ currentPageNum }} / {{ Math.ceil(total / per_page) }} 页
        </div>
        <div class="pagination-controls">
          <button @click="handlePaginationChange(1)" :disabled="currentPageNum === 1" class="pagination-btn">
            首页
          </button>
          <button @click="handlePaginationChange(currentPageNum - 1)" :disabled="currentPageNum === 1"
            class="pagination-btn">
            上一页
          </button>

          <div class="page-numbers">
            <button v-for="page in getPageNumbers()" :key="page" @click="handlePaginationChange(page)"
              :class="['page-number', { active: page === currentPageNum }]">
              {{ page }}
            </button>
          </div>

          <button @click="handlePaginationChange(currentPageNum + 1)"
            :disabled="currentPageNum >= Math.ceil(total / per_page)" class="pagination-btn">
            下一页
          </button>
          <button @click="handlePaginationChange(Math.ceil(total / per_page))"
            :disabled="currentPageNum >= Math.ceil(total / per_page)" class="pagination-btn">
            末页
          </button>
        </div>

        <div class="page-size-selector">
          <select @change="handlePageSizeChange(Number($event.target.value))" :value="per_page">
            <option value="10">10条/页</option>
            <option value="20">20条/页</option>
            <option value="50">50条/页</option>
            <option value="100">100条/页</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 数据整合中心页面 -->
    <DataIntegration v-if="currentPage === 'data'" />
    
    <!-- 项目告警页面 -->
    <ProjectAlerts v-if="currentPage === 'alerts'" />
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Navigation from './components/Navigation.vue'
import Header from './components/Header.vue'
import StatsBar from './components/StatsBar.vue'
import Controls from './components/Controls.vue'
import MainContent from './components/MainContent.vue'
import DataIntegration from './components/DataIntegration.vue'
import ProjectAlerts from './components/ProjectAlerts.vue'
import CreateProjectModal from './components/CreateProjectModal.vue'
import AuthGuard from './components/AuthGuard.vue'
import type { Project, ProjectStatus, Stats } from './types'
import { api } from './api'
import { mockApi, isMockMode } from './api/mock'
import { projectsApi } from './api/services/projects'
import { useToast } from './composables/useToast'
import { useAuth } from './composables/useAuth'

// 授权状态
const { isAuthenticated, setAuthenticated } = useAuth()

// 当前页面状态
const currentPage = ref<'projects' | 'data' | 'alerts'>('projects')

// 数据状态
const projects = ref<Project[]>([])
const stats = ref<Stats>({ total: 0, active: 0, completed: 0, pending: 0 })
const loading = ref(false)
const error = ref<string | null>(null)

// 消息提示
const { success, error: showError } = useToast()

// 筛选状态
const activeFilter = ref<ProjectStatus | 'all' | 'overdue'>('all')
const searchQuery = ref('')

// 分页状态
const currentPageNum = ref(1)
const per_page = ref(10)
const total = ref(0)

// 创建项目弹窗状态
const createModalVisible = ref(false)

// 过滤项目 (现在由服务端处理分页和筛选)
const filteredProjects = computed(() => {
  return projects.value
})

// 获取项目列表
const fetchProjects = async (showSuccessToast = true) => {
  try {
    loading.value = true
    error.value = null

    // 构建请求参数
    const params: any = {
      page: currentPageNum.value,
      per_page: per_page.value,
      customer_name: searchQuery.value
    }

    // 处理逾期项目的特殊逻辑
    if (activeFilter.value === 'overdue') {
      // 获取今日日期，格式为 YYYY-MM-DD
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      params.overdue = `${year}-${month}-${day}`
    } else if (activeFilter.value !== 'all') {
      params.vika_status = activeFilter.value
    }

    const response = await projectsApi.getList(params)

    projects.value = response.data.list
    total.value = response.data.total

    // 只在需要时显示成功提示
    if (showSuccessToast) {
      success('数据加载成功', `已加载 ${response.data.list.length} 条项目记录`)
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取项目列表失败'
    showError('获取项目列表失败', err instanceof Error ? err.message : '请稍后重试')
    console.error('获取项目列表失败:', err)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = isMockMode
      ? await mockApi.projects.getStats()
      : await api.projects.getStats()

    stats.value = response.data
  } catch (err) {
    console.error('获取统计数据失败:', err)
  }
}

// 事件处理
const handleFilterChange = async (filter: ProjectStatus | 'all' | 'overdue') => {
  activeFilter.value = filter
  currentPageNum.value = 1 // 重置到第一页
  await fetchProjects()
}

const handleSearchChange = async (query: string) => {
  searchQuery.value = query
  currentPageNum.value = 1 // 重置到第一页
  await fetchProjects()
}

// 分页事件处理
const handlePaginationChange = async (page: number) => {
  currentPageNum.value = page
  await fetchProjects()
}

const handlePageSizeChange = async (size: number) => {
  per_page.value = size
  currentPageNum.value = 1 // 重置到第一页
  await fetchProjects()
}

const handleUpdateProject = async (updatedProject: Project) => {
  try {
    if (isMockMode) {
      // Mock 模式下直接更新本地数据
      const index = projects.value.findIndex(p => p.id === updatedProject.id)
      if (index !== -1) {
        projects.value[index] = updatedProject
      }
      success('项目更新成功', `项目 "${updatedProject.customer_name}" 已更新`)
    } else {
      // 真实 API 调用
      await api.projects.update(updatedProject.id, updatedProject)
      await fetchProjects()
      await fetchStats()
      success('项目更新成功', `项目 "${updatedProject.customer_name}" 已更新`)
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '更新项目失败'
    showError('更新项目失败', err instanceof Error ? err.message : '请稍后重试')
    console.error('更新项目失败:', err)
  }
}

const handleDeleteProject = async (projectToDelete: Project) => {
  try {

      // 真实 API 调用
      await api.projects.delete(projectToDelete.id)
      await fetchProjects()
      await fetchStats()
      success('项目删除成功', `项目 "${projectToDelete.customer_name}" 已删除`)
  } catch (err) {
    error.value = err instanceof Error ? err.message : '删除项目失败'
    showError('删除项目失败', err instanceof Error ? err.message : '请稍后重试')
    console.error('删除项目失败:', err)
  }
}

const handleNavigationChange = (page: 'projects' | 'data' | 'alerts') => {
  currentPage.value = page
}

// 创建项目相关处理函数
const handleCreateProject = () => {
  createModalVisible.value = true
}

const handleCreateProjectSubmit = async (projectData: Omit<Project, 'id' | 'created_time' | 'updated_time'>) => {
  try {
    if (isMockMode) {
      // Mock 模式下直接添加到本地数据
      const newProject: Project = {
        ...projectData,
        id: Date.now(), // 简单的ID生成
        created_time: new Date().toISOString(),
        updated_time: new Date().toISOString()
      }
      projects.value.unshift(newProject)
      total.value += 1
      success('项目创建成功', `项目 "${projectData.customer_name}" 已创建`)
    } else {
      // 真实 API 调用 - 需要转换数据格式
      const apiData = {
        name: projectData.customer_name,
        description: `${projectData.customer_name} - ${projectData.project_type}`,
        code: projectData.project_code,
        manager: projectData.customer_manager || '',
        status: projectData.status,
        progress: 0,
        startDate: projectData.start_date || '',
        endDate: projectData.end_date || '',
        budget: projectData.contract_amount ? `${projectData.contract_amount}元` : '',
        customerName: projectData.customer_name,
        customerDomain: projectData.customer_domain,
        projectType: projectData.project_type,
        contractTerms: projectData.contract_terms
      }
      await api.projects.create(apiData)
      await fetchProjects()
      await fetchStats()
      success('项目创建成功', `项目 "${projectData.customer_name}" 已创建`)
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '创建项目失败'
    showError('创建项目失败', err instanceof Error ? err.message : '请稍后重试')
    console.error('创建项目失败:', err)
  }
}

// 授权验证成功处理
const handleAuthorized = async () => {
  setAuthenticated()
  // 授权成功后立即加载数据
  await Promise.all([
    fetchProjects(false), // 不显示成功提示
    fetchStats()
  ])
}

// 获取分页页码数组
const getPageNumbers = () => {
  const totalPages = Math.ceil(total.value / per_page.value)
  const current = currentPageNum.value
  const pages: number[] = []

  // 显示逻辑：当前页前后各显示2页
  const start = Math.max(1, current - 2)
  const end = Math.min(totalPages, current + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
}

// 初始化数据
onMounted(async () => {
  // 只有在已授权的情况下才加载数据
  if (isAuthenticated.value) {
    await Promise.all([
      fetchProjects(),
      fetchStats()
    ])
  }
})
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: #fff;
  color: #333;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.pagination-btn:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #999;
}

.pagination-btn:disabled {
  background: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
  border-color: #eee;
}

.page-numbers {
  display: flex;
  gap: 4px;
  margin: 0 8px;
}

.page-number {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: #fff;
  color: #333;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  min-width: 36px;
  text-align: center;
  transition: all 0.2s;
}

.page-number:hover {
  background: #f5f5f5;
  border-color: #999;
}

.page-number.active {
  background: #007bff;
  color: #fff;
  border-color: #007bff;
}

.page-size-selector select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
  color: #333;
  font-size: 14px;
  cursor: pointer;
}

.page-size-selector select:focus {
  outline: none;
  border-color: #007bff;
}

@media (max-width: 768px) {
  .pagination-container {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .pagination-controls {
    justify-content: center;
    flex-wrap: wrap;
  }

  .page-numbers {
    margin: 0;
  }
}
</style>